<?php

namespace app\api\controller\app;

use app\admin\model\AssistantOrder;
use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\CallService;
use app\api\service\DeviceService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Assistant extends Api
{
    protected $noNeedLogin = ['sxfOrderCallback','getList','detail','initList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function getListV2()
    {

        $ret = array();
        $this->success('',$ret);
    }


    public function getList()
    {

        $page = $this->request->param('page');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $sex = $this->request->param('sex');

        $where = " and sex ='".$sex."'";
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $sql = "select * from(
SELECT id,name,type,logo,lng,lat,level,price,sex,tag,city,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_assistant where `status` !='verifying' $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";

        $assistantModel = new \app\admin\model\Assistant();
        $list = $assistantModel->query($sql);

        foreach ($list as $key=>$val){
            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $tags = explode(",", $val['tag']);
            $t = "";
            foreach ($tags as $k=>$v){
                $t = $t.$v;
                if(count($tags)-1 != $k){
                    $t = $t." | ";
                }
            }
            $list[$key]['tag'] = $t;
            $types = explode(",",$val['type']);
            $list[$key]['type'] = $types;
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";
            }

        }
        $this->success('',$list);
    }

    public function detail()
    {

        $id = $this->request->param('id');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $assistAntModel =  new \app\admin\model\Assistant();
        $assist = $assistAntModel->where('id',$id)->find();
        if(!$assist) $this->error("助教不存在");

        $image = explode(",",$assist['image']);
        foreach ($image as $key=>$val){
            $image[$key] = cdnurl($val,true);
        }
        $assist['image'] = $image;
        $assist['logo'] = cdnurl($assist['logo'],true);


        $tags = explode(",", $assist['tag']);
        $t = "";
        foreach ($tags as $k=>$v){
            $t = $t.$v;
            if(count($tags)-1 != $k){
                $t = $t." | ";
            }
        }
        $assist['tag'] = $t;
        $types = explode(",",$assist['type']);
        $assist['type'] = $types;


        $page = 1;
        $limit = 5;
        $offset = ($page - 1) * $limit;

        $sql = "select * from(
SELECT id,name,address,logo,lng,lat,tel,is_table,status,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` !='-1' and is_table = 1) as tmp_table_name
order by distance LIMIT $offset ,$limit";

        $tableModel = new \app\admin\model\Shoptable();
        $list = $tableModel->query($sql);
        foreach ($list as $key=>$val){
            if(isset($val['distance'])){
                $list[$key]['distance'] = round($val['distance']/1000,2)."km";

            }else{
                $list[$key]['distance'] = "";

            }
        }
        $assist['shopList'] = $list;


        $date = getFiveDate();
        $assist['date'] = $date;
        $this->success('',$assist);

    }

    public function getTimeList()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');

        $where = array();
        $orderModel = new AssistantOrder();
        $start =$date." 00:00:00";
        $end =$date." 23:59:59";
        $where['create_time'] = array("between",array(strtotime($start),strtotime($end)));

        $list = $orderModel->where('assistant_id',$id)->where($where)->where('status','in',['payed','doing','taked'])->select();
        $timeList = array();
        $current_hour = date('H');
        $today = date("Y-m-d");
        for($i = 0;$i<24;$i++){
            $start = $i.":00";
            $end = ($i+1).":00";
            $obj = array();
            $obj['start'] = $start;
            $obj['end'] = $end;
            $obj['disabled'] = false;
            if($today == $date && $i<=$current_hour){
                $obj['disabled'] = true;
            }
            $start2 = strtotime($date." ".$start);
            $end2 = strtotime($date." ".$end);

            $isDis = false;
            foreach ($list as $k=>$v){
                if($v['start_time'] >= $start2 && $end2 <= $v['end_time'] && $end2 >$v['start_time']){
                    $isDis = true;
                }
                if($v['start_time'] < $start2 && $end2 <= $v['end_time'] && $end2 >$v['start_time']){
                    $isDis = true;
                }
            }
            if($isDis){
                $obj['disabled'] = true;
            }


            $obj['active'] = false;
            $obj['curClass'] = false;
            $timeList[] = $obj;
        }
        $this->success('',$timeList);

    }


    public function addOrder()
    {

        $id = $this->request->param('id');
        $startTime = $this->request->param('startTime');
        $endTime = $this->request->param('endTime');
        $shop_id = $this->request->param('shopId');

        $assistAntModel =  new \app\admin\model\Assistant();
        $assist = $assistAntModel->where('id',$id)->find();
        $price = $assist['price'];
        if($assist['status'] != 'verifyed'){
            $this->error("此助教已休息，暂不接单");
        }
        $hour = (strtotime($endTime)- strtotime($startTime))/3600;
        $user = $this->auth->getUser();
        $amount =$hour*$price;
        $orderNo = getOrderSn();
        $db = array();
        $db['assistant_id'] = $id;
        $db['user_id'] = $user['id'];
        $db['shop_id'] = $shop_id;
        $db['start_time'] = strtotime($startTime);
        $db['end_time'] = strtotime($endTime);
        $db['amount'] = $amount;
        $db['pay_amount'] = $amount;
        $db['create_time'] = time();
        $db['tip'] = 0;
        $db['distance'] = 0;
        $db['order_no'] = $orderNo;

        $assistAntOrerModel = new AssistantOrder();
        $orderId = $assistAntOrerModel->insertGetId($db);
        if($orderId){

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/assistant/sxfOrderCallback";

            $orgModel = new Org();
            $org = $orgModel->where('id', 27)->find();
            $mno = $org['mno'];

            $req['mno'] = $mno;
            $req['ordNo'] = $orderNo;
            $req['amt'] = formatMoney($amount);

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];

            $req['subject'] = "台球预定助教";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            error_log("==pay==".$res);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];


            if ($bizCode == '0000') {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = $result['respData'];
                $this->success('',$info);
            } else {
                $this->error($bizMsg);
            }
        }else{
            $this->error("提交订单失败");
        }
    }

    public function sxfOrderCallback()
    {
        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $assistAntOrerModel = new AssistantOrder();
            $order = $assistAntOrerModel->where('order_no',$out_trade_no)->find();
            $assistAntOrerModel->where('order_no',$out_trade_no)->update(['status'=>'payed']);


            $callService  =new  CallService();
            $callService->call($order);
        }
    }

    public function orderDetail()
    {

        $order_no =$this->request->param('orderNo');
        $assistantOrderModel = new AssistantOrder();
        $order = $assistantOrderModel->where('order_no',$order_no)->find();
        $shopModel = new Shop();
        $shop = $shopModel->where('id',$order['shop_id'])->find();
        $order['shop'] = $shop;


        $assistAntModel = new \app\admin\model\Assistant();
        $assistant = $assistAntModel->where('id',$order['assistant_id'])->find();
        $assistant['logo'] = cdnurl($assistant['logo'],true);
        $order['assistant'] = $assistant;

        $hour = ($order['end_time']- $order['start_time'])/3600;
        $order['hour'] = $hour;
        $this->success('',$order);
    }


    public function assistOrderList()
    {

        $status = $this->request->param('status');
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $user = $this->auth->getUser();
        $assistOrderModel = new AssistantOrder();
        $assistAntModel = new \app\admin\model\Assistant();
        $shopModel = new Shop();

        $where = array();
        $where['user_id'] = $user['id'];
        if($status != ""){
            $where['status'] = $status;

        }


        $list = $assistOrderModel->where($where)->order('create_time','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){
            $shop = $shopModel->where('id',$val['shop_id'])->find();
            $list[$key]['shop']= $shop;

            $assistant = $assistAntModel->where('id',$val['assistant_id'])->find();
            $hour = ($val['end_time']- $val['start_time'])/3600;
            $list[$key]['hour'] = $hour;
            $assistant['logo'] = cdnurl($assistant['logo'],true);
            $list[$key]['assistant'] = $assistant;

            $list[$key]['start'] = date("Y-m-d H:i",$val['start_time']);
            $list[$key]['end'] = date("Y-m-d H:i",$val['end_time']);


        }

        $this->success('',$list);
    }

    public function cancelOrder()
    {

        $order_no  = $this->request->param('order_no');
        $assistOrderModel = new AssistantOrder();
        $order = $assistOrderModel->where('order_no',$order_no)->find();
        if(!$order) $this->error("订单不存在");
        if($order['status'] == 'taked' || $order['status'] == 'done') $this->error("此状态订单不可取消");

        $assistOrderModel->where('id',$order['id'])->update(['status'=>'cancel']);

        $this->success('');
    }

    public function initList()
    {

        $ret = array();
        $ret[] = "中式台球";
        $ret[] = "斯洛克";


        $tag = array();

        $tag[] = "球技好";
        $tag[] = "善良可爱";
        $tag[] = "帅气";
        $tag[] = "姿势特帅";
        $tag[] = "非常热爱";
        $tag[] = "美丽大方";
        $tag[] = "性感";

        $tags = array();
        foreach ($tag as $key=>$val){
            $obj  = array();
            $obj['value'] = $val;
            $obj['check'] = false;
            $tags[] = $obj;
        }


        $result = array();
        $result['type'] = $ret;
        $result['tag'] = $tags;

        $this->success('',$result);

    }


    public function add()
    {

        $user = $this->auth->getUser();
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $sex = $this->request->param('sex');
        $birth = $this->request->param('birth');
        $address = $this->request->param('address');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $type = $this->request->param('type');
        $level = $this->request->param('level');
        $time1 = $this->request->param('time1');
        $time2 = $this->request->param('time2');
        $intro = $this->request->param('intro');
        $logo = $this->request->param('logo');
        $cover = $this->request->param('cover');
        $tag = $this->request->param('tag');
        $city = $this->request->param('city');
        $price = $this->request->param('price');
        $tag = json_decode(htmlspecialchars_decode($tag), true);
        $cover = json_decode(htmlspecialchars_decode($cover), true);

        if($sex == 2){
            $sex = "girl";
        }else{
            $sex = "boy";
        }
        if($level == 1){
            $level = "萌新";
        }else if($level == 2){
            $level = "业余";
        }else{
            $level = "专业";
        }
        $tagStr = "";
        foreach ($tag as $key=>$val){
            $tagStr = $tagStr.$val;
            if($key != count($tag)-1){
                $tagStr = $tagStr.",";
            }
        }

        $coverStr = "";
        foreach ($cover as $key=>$val){
            $val =  str_replace("https://img.quexiaqp.com", "", $val);
            $coverStr = $coverStr.$val;
            if($key != count($cover)-1){
                $coverStr = $coverStr.",";
            }
        }
        $logo = str_replace("https://img.quexiaqp.com", "", $logo);
        $assistantModel = new \app\admin\model\Assistant();
        $db = array();
        $db['user_id'] = $user['id'];
        $db['name'] = $name;
        $db['mobile'] = $mobile;
        $db['sex'] = $sex;
        $db['type'] = $type;
        $db['level'] = $level;
        $db['birth'] = $birth;
        $db['logo'] = $logo;
        $db['image'] = $coverStr;
        $db['intro'] = $intro;
        $db['tag'] = $tagStr;
        $db['lat'] = $lat;
        $db['lng'] = $lng;
        $db['address'] = $address;
        $db['city'] = $city;
        $db['price'] = $price;
        $db['time'] = $time1;
        $db['time2'] = $time2;

        $assistantModel->insert($db);

        $this->success('成功');



    }



}
